//
//  ADRollingView.m
//  ADRollingView
//
//  Created by 美鑫科技 on 16/6/21.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "ADRollingView.h"

static NSString *cellIdent = @"cellIdent";

@interface ADRollingView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *iconArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger currentIndex;

@end

@implementation ADRollingView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.currentIndex = 1;
        [self initSubView];
        [self startTimer];
    }
    return self;
}

// 广告标题初始化
- (instancetype)initWithTitles:(NSArray *)titles Frame:(CGRect)frame{
    self.titleArray = titles.mutableCopy;
     id tFirstObject = [titles firstObject];
    if (tFirstObject) {
        [self.titleArray addObject:tFirstObject];
    } else{
        [self.titleArray addObject:@""];
    }
    return [self initWithFrame:frame];
}

// 带图标初始化
- (instancetype)initWithIcons:(NSArray *)icons Titles:(NSArray *)titles Frame:(CGRect)frame{
    self.titleArray = titles.mutableCopy;
    id tFirstObject = [titles firstObject];
    if (tFirstObject) {
        [self.titleArray addObject:tFirstObject];
    } else{
        [self.titleArray addObject:@""];
    }
    self.iconArray = icons.mutableCopy;
    id iFirstObject = [icons firstObject];
    if (iFirstObject) {
        [self.iconArray addObject:iFirstObject];
    } else{
        [self.iconArray addObject:@""];
    }
    return [self initWithFrame:frame];
}

// 初始化滚动view
- (void)initSubView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.pagingEnabled = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdent];
    [self addSubview:_tableView];
}

#pragma mark --UIScrollViewDelegate--

// 手动拖拽的时候停止计时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}

// 手动拖拽结束后重新开始计时
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self startTimer];
    // 从拖拽完成地方开始继续滚动
    self.currentIndex = scrollView.contentOffset.y / (self.frame.size.height * 1.0f);
}

#pragma mark --UITableViewDataSource--

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent forIndexPath:indexPath];
    cell.textLabel.text = self.titleArray[indexPath.row];
    
    if (self.iconArray.count > 0) {
        id item = self.iconArray[indexPath.row];
        if ([item isKindOfClass:[UIImage class]]) {
            cell.imageView.image = item;
        }else if([item isKindOfClass:[NSURL class]]){
            // 子线程中加载网络图片数据
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData *data = [NSData dataWithContentsOfURL:item];
                // 加载完成后回到主线程更新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImage *image = [UIImage imageWithData:data];
                    cell.imageView.image = image;
                });
            });
        }else if ([item isKindOfClass:[NSString class]]){
            // 判断是否是本地图片资源
            UIImage *imageWithName = [UIImage imageNamed:item];
            if (imageWithName) {
                cell.imageView.image = imageWithName;
            }else{
                // 子线程中加载网络图片数据
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item]];
                    // 加载完成后回到主线程更新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [UIImage imageWithData:data];
                        cell.imageView.image = image;
                    });
                });
            }
        }else{
            NSAssert(0, @"没有匹配的数据类型!");
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark --UITableViewDelegate--

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_delegate && [_delegate respondsToSelector:@selector(rollingView:didSelectIndex:)]) {
        [_delegate rollingView:self didSelectIndex:indexPath.row];
    }
}

- (NSMutableArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

- (NSMutableArray *)iconArray{
    if (!_iconArray) {
        _iconArray = [NSMutableArray array];
    }
    return _iconArray;
}

#pragma mark -timerMethod

// 开始计时
- (void)startTimer{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeClick) userInfo:nil repeats:YES];
}

// 停止计时
- (void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}

// 计时事件
- (void)timeClick{
    if (self.currentIndex == self.titleArray.count) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
        self.currentIndex = 1;
    }
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    self.currentIndex++;
}

@end